package org.hk.proxy.server.web.handler;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.EncryptUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import org.hk.proxy.common.constant.ApiStateEnum;
import org.hk.proxy.common.json.JSON;
import org.hk.proxy.server.db.entity.HkProxyUser;
import org.hk.proxy.server.db.mapper.HkProxyUserMapper;
import org.hk.proxy.server.utils.SpringUtils;
import org.hk.proxy.server.web.Result;
import org.hk.proxy.server.web.interceptor.LoginInterceptor;

import java.util.Map;

public class LoginHandler implements RequestHandler{
    public static final String AuthHeader="Authorization";
    private HkProxyUserMapper userMapper;
    @Override
    public Result request(HttpRequest request) {
        if (userMapper == null) {
            userMapper = SpringUtils.getBean("hkProxyUserMapper",HkProxyUserMapper.class);
        }
        FullHttpRequest fullHttpRequest = (FullHttpRequest) request;
        byte[] buf = new byte[fullHttpRequest.content().readableBytes()];
        fullHttpRequest.content().readBytes(buf);
        String config = new String(buf);
        String token = IdUtil.fastSimpleUUID();
        if (StrUtil.isNotBlank(config)) {
            Map<String, String> loginParams = JSON.parseObject(config, Map.class);
            if (loginParams != null) {
                String username = loginParams.get("username");
                String password = loginParams.get("password");
                String realPwd = EncryptUtils.md5Base64(password);
                HkProxyUser user = userMapper.selectOne(Wrappers.<HkProxyUser>lambdaQuery().eq(HkProxyUser::getUserName, username).eq(HkProxyUser::getPwd, realPwd));
                if (user != null) {
                  //  fullHttpRequest.headers().set(HttpHeaderNames.COOKIE, token);
                    LoginInterceptor.userMap.put(token, user);
                    return Result.success(token);
                } else {
                    return Result.of(ApiStateEnum.ACCOUNT_PWD_ERROR);
                }
            }
        }
        return Result.of(ApiStateEnum.PARM_ERROR);
    }
}
